package com.GreenIce.android.util;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

public class HeadSetManager extends BroadcastReceiver{
	static HeadSetManager inst;
	public static HeadSetManager getInstance(){
		if (inst == null)
			inst = new HeadSetManager();
		return inst;
	}
	public static void setHandler(Handler handler){
		getInstance().handler = handler;
	}
	public static void enable(){
		getInstance().enable = true;
	}
	public static void disable(){
		getInstance().enable = false;
	}
	private Handler handler;
	private boolean enable;
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Log.i("headset", "get an event");
		if (enable){
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
				if(intent.getIntExtra("state", 0) == 0){
					handler.sendEmptyMessage(0);
				}
			}
		}		
	}
	public boolean isPlug(){
		String HEADSET_STATE_PATH = "/sys/class/switch/h2w/state";
		int headsetState = 0;
		try {
			FileReader file = new FileReader(HEADSET_STATE_PATH);
			char[] buffer = new char[1024];
            int len = file.read(buffer, 0, 1024);
            headsetState = Integer.valueOf((new String(buffer, 0, len)).trim());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(headsetState == 0)
			return false;
		else
			return true;
	}
	

}
